<template>
  <div v-loading="loading" class="purchase">
    <searchHead
      v-if="requestType <= 3"
      :search-data="searchData"
      :request-type="requestType"
      @search="handleCurrentChange(1)"
      @reset="reset"
      @download="download"
    />
    <searchHead2 v-else :search-data="searchData" :isbrand-name="true" @search="handleCurrentChange(1)" @reset="reset" @download="download" />
    <essTable
      ref="table"
      :thead-list="theadList"
      :other-container-box="otherContainerBox"
      :resize-observer-ele="resizeObserverEle"
      :page-num="searchData.pageNum - 1 + 2"
      :total="total"
      :data-list="dataList"
      @handleCurrentChange="handleCurrentChange"
      @handleSizeChange="handleSizeChange"
      @examine="examine"
      @operationLog="operationLog"
    >
      <template v-slot:channelId="{ scope }">
        {{ scope.row.channelId | channelNameById }}
      </template>
      <template v-slot:mainStatus="{ scope }">
        <span>{{ scope.row.mainStatus | mainStatus }}</span>
      </template>
      <template v-slot:operationCode="{ scope }">
        <span>{{ scope.row.operationCode | operationCodes }}</span>
      </template>
    </essTable>
    <operation-log ref="operationLogRef" :process-data-list="processDataList" />
    <operation-log2 ref="operationLogRef2" :table-data="processDataList" :log-list="commodityMaintainLog">
      <template v-slot:createdTime="{ scope }">
        {{ transDate(scope.row.createdTime) }}
      </template>
    </operation-log2>
  </div>
</template>

<script>
import searchHead from '@/views/coi/approve/components/searchHead.vue'
import searchHead2 from '@/views/coi/approve/components/searchHead2.vue'
import essTable from '@/components/eTable/eTable.vue'
import { stringToArray } from '@/utils/processingData'
import { approveTableList, firstTrialList, firstTrialList1 } from '@/views/coi/commonJs/tableHeadList'
import bus from '@/utils/eventBus.js'
import operationLog from '@/views/coi/approve/components/operationLog.vue'
import operationLog2 from '@/views/coi/components/operationLog.vue'
import {
  purchaseApprovalList,
  complianceApprovalList,
  processData,
  purchaseReviewExport,
  complianceExport,
  findBuyerAuditSkuProcessPage,
  findComplianceAuditSkuProcessPage,
  operationLogByProcessId,
  exportData
} from '@/api/coi/onlineTaskAPI/sku'
import { createGoodsTypeKind, createGoodsStatus, taskTypes, commodityTypes, operationCodes } from '@/views/coi/commonJs/dictionary'
import { commodityMaintainLog } from '@/views/coi/commonJs/operationLogList'
import moment from 'moment'
import { filterKey } from '@/utils/processingData'

export default {
  components: {
    searchHead,
    searchHead2,
    essTable,
    operationLog,
    operationLog2
  },
  filters: {
    channelNameById(v) {
      return filterKey(v, taskTypes)
    },
    mainStatus(v) {
      for (let i = 0; i < commodityTypes.length; i++) {
        const el = commodityTypes[i]
        if (el.value === v) {
          return el.label
        }
      }
    },
    operationCodes(v) {
      for (let i = 0; i < operationCodes.length; i++) {
        const el = operationCodes[i]
        if (el.value === v) {
          return el.label
        }
      }
    }
  },
  props: {
    page: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      otherContainerBox: ['.app-container', '.checkComponent'],
      resizeObserverEle: ['.app-main', '.app-container'],
      searchData: {},
      total: 0,
      dataList: [],
      loading: false,
      commodityMaintainLog,
      processDataList: [] // 操作日志
    }
  },
  computed: {
    // 1 是采购， 2 是合规 3:线上建品状态  4:初审  5终审
    requestType() {
      let flag = null
      switch (this.page) {
        case 'trial':
          flag = 1
          break
        case 'final':
          flag = 2
          break
        case 'trial2':
          flag = 4
          break
        case 'final2':
          flag = 5
          break
        default:
          break
      }
      return flag
    },
    theadList() {
      console.log('***************', this.page)
      if (this.page === 'final2') {
        return firstTrialList1
      } else if (this.page === 'trial2') {
        return firstTrialList
      } else {
        return approveTableList
      }
    }
  },
  watch: {
    page: {
      handler(newValue) {
        this.dataList = []
        this.initalData()
        this.handleCurrentChange(1)
      }
    }
  },
  activated() {
    this.handleCurrentChange(1)
  },
  created() {
    this.initalData()
    this.handleCurrentChange(1)
  },
  methods: {
    initalData() {
      const searchData = {
        pageNum: 0,
        pageSize: 10
      }
      if (this.page === 'trial') searchData.mainStatus = '5000'
      else if (this.page === 'final') searchData.mainStatus = '6000'
      else if (this.page === 'trial2') searchData.mainStatusList = [9020]
      else if (this.page === 'final2') searchData.mainStatusList = [9030]
      this.searchData = searchData
    },
    // 状态码key值转成对应状态
    filters(value, arr) {
      const newarr = arr.filter((item) => item.value === value)
      if (newarr.length) return newarr[0].label
      else return ''
    },
    handleQueryData() {
      const searchData = JSON.parse(JSON.stringify(this.searchData))
      if (Array.isArray(searchData.createByDate)) {
        searchData.startCreatedTime = searchData.createByDate[0]
        searchData.endCreateTime = searchData.createByDate[1]
      }
      if (Array.isArray(searchData.updataByDate)) {
        searchData.startUpdatedTime = searchData.updataByDate[0]
        searchData.endUpdateTime = searchData.updataByDate[1]
      }
      if (this.requestType > 3) {
        if (Array.isArray(searchData.createByDate)) {
          searchData.startCreateTime = searchData.createByDate[0]
        }
        searchData.skuList = stringToArray(searchData.skuList, /[\n\r]/) // upc(不含检验码)
        searchData.upcList = stringToArray(searchData.upcList, /[\n\r]/) // upc(含检验码)
        searchData.finelineNbrList = stringToArray(searchData.finelineNbrList, /[\n\r]/)
        searchData.buildVendorNbrList = stringToArray(searchData.buildVendorNbrList, /[\n\r]/)
        if ('startCreatedTime' in searchData) delete searchData.startCreatedTime
        for (const key in searchData) {
          if (typeof searchData[key] !== 'number' && !searchData[key].length) {
            delete searchData[key]
          }
        }
      }
      if ('updataByDate' in searchData) delete searchData.updataByDate
      if ('createByDate' in searchData) delete searchData.createByDate
      return searchData
    },
    // 点击检索按钮执行
    async search() {
      try {
        this.loading = true
        const { result } = await this.query(this.handleQueryData())
        if (result) {
          this.total = result.total
          this.dataList = result.data
          const _this = this
          this.dataList.forEach((item) => {
            item.createdTime = _this.transDate(item.createdTime)
            item.updatedTime = _this.transDate(item.updatedTime)
            item.mainStatusDec = _this.filters(item.mainStatus, createGoodsStatus)
            item.creationWayDec = _this.filters(item.creationWay, createGoodsTypeKind)
          })
        }
      } finally {
        this.loading = false
      }
    },
    transDate(v) {
      if (v === null) {
        return ''
      }
      return moment(v).format('YYYY-MM-DD HH:mm:ss')
    },
    async query(searchData) {
      if (this.requestType === 1) return await purchaseApprovalList(searchData)
      else if (this.requestType === 2) return await complianceApprovalList(searchData)
      else if (this.requestType === 3) return await complianceApprovalList(searchData)
      else if (this.requestType === 4) return await findBuyerAuditSkuProcessPage(searchData)
      else if (this.requestType === 5) return await findComplianceAuditSkuProcessPage(searchData)
    },
    // 重置检索条件
    reset() {
      this.initalData()
      this.search()
    },
    // 导出
    async download() {
      try {
        this.loading = true
        const searchData = this.handleQueryData()
        const date = moment(new Date()).format('YYYY-MM-DD')
        switch (this.requestType) {
          case 1:
            await purchaseReviewExport(searchData, `线上商品建品 ${date}`)
            break
          case 2:
            await complianceExport(searchData, `线上商品建品 ${date}`)
            break
          case 4:
            await exportData(searchData, `线上商品初审 ${date}`)
            break
          case 5:
            await exportData(searchData, `线上商品终审 ${date}`)
            break
          default:
            break
        }
      } finally {
        this.loading = false
      }
    },
    // 分页器
    handleCurrentChange(val) {
      this.searchData.pageNum = val - 1
      this.search()
    },
    handleSizeChange(val) {
      this.searchData.pageSize = val
      this.handleCurrentChange(1)
    },
    // 操作日志
    async operationLog({ row }) {
      const { result } = this.requestType > 3 ? await operationLogByProcessId(row.id) : await processData(row.id)
      if (Array.isArray(result) && result.length) {
        if (this.requestType > 3) {
          this.$refs.operationLogRef2.dialogVisible = true
        } else {
          this.$refs.operationLogRef.dialogVisible = true
        }
        this.processDataList = result
      } else {
        this.$message({
          type: 'warning',
          message: '未查询到该商品线上建品的操作日志'
        })
      }
    },
    // 列表查看按钮事件
    async examine({ row }) {
      bus.$emit('setTagName', row.skuName)
      if (this.requestType > 3) {
        this.$router.push({
          path: `/commodityM/approve-detail/${row.id}/${row.mainStatus}/${this.$route.name}/${this.page}/${row.channelId}`
        })
      } else {
        this.$router.push({
          path: `/approvalDetails/${row.id}/${row.mainStatus}/${this.$route.name}/${this.page}`
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.purchase {
  height: calc(100%);
}
/deep/ .el-dialog__body {
  padding: 10px 20px;
  overflow-y: auto;
  max-height: 75vh;
}
/deep/ .el-dialog__footer {
  padding: 10px 20px;
}
.details {
  /deep/ .el-dialog__body {
    padding: 0;
    padding-bottom: 20px;
  }
}
.remark {
  margin: 8px 0;
  display: flex;
  justify-content: flex-start;
  .remarkTitle {
    width: 70px;
    line-height: 20px;
  }
  .remarkList {
    flex: 1;
    line-height: 20px;
  }
}
</style>
